import 'package:flutter/material.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

class PPAssetPicker {
  static Future<List<AssetEntity>?> show(
    BuildContext context, {
    int maxAssets = 9, // 资源选择的最大数量
    RequestType requestType = RequestType.image, // 请求的资源类型
    List<AssetEntity>? selectedAssets, // 已选中的资源
    bool allowCapture = true, // 是否允许拍照
    AssetPickerPageRouteBuilder<List<AssetEntity>>? pageRouteBuilder,
  }) {
    dynamic specialItemBuilder;
    if (allowCapture) {
      const AssetPickerTextDelegate textDelegate = AssetPickerTextDelegate();
      specialItemBuilder = (
        BuildContext context,
        AssetPathEntity? path,
        int length,
      ) {
        if (path?.isAll != true) {
          return null;
        }
        return Semantics(
          label: textDelegate.sActionUseCameraHint,
          button: true,
          onTapHint: textDelegate.sActionUseCameraHint,
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () async {
              final AssetEntity? result = await _pickFromCamera(context);
              if (result == null) {
                return;
              }
              final AssetPicker<AssetEntity, AssetPathEntity> picker =
                  context.findAncestorWidgetOfExactType()!;
              final DefaultAssetPickerBuilderDelegate builder =
                  picker.builder as DefaultAssetPickerBuilderDelegate;
              final DefaultAssetPickerProvider p = builder.provider;
              await p.switchPath(
                PathWrapper<AssetPathEntity>(
                  path: await p.currentPath!.path.obtainForNewProperties(),
                ),
              );
              p.selectAsset(result);
              if (maxAssets == 1) {
                // 当时拍照，并且只能选择1个数据的情况下，直接返回
                Navigator.of(context).pop(<AssetEntity>[result]);
              }
            },
            child: const Center(
              child: Icon(Icons.camera_enhance, size: 42.0),
            ),
          ),
        );
      };
    }

    var pickerConfig = AssetPickerConfig(
      textDelegate: const AssetPickerTextDelegate(), // 设置中文
      maxAssets: maxAssets,
      requestType: requestType,
      selectedAssets: selectedAssets,
      specialPickerType: SpecialPickerType.noPreview,
      specialItemPosition:
          allowCapture ? SpecialItemPosition.prepend : SpecialItemPosition.none,
      specialItemBuilder: specialItemBuilder,
    );

    return AssetPicker.pickAssets(
      context,
      pickerConfig: pickerConfig,
    );
  }
}

Future<AssetEntity?> _pickFromCamera(BuildContext c) {
  return CameraPicker.pickFromCamera(
    c,
    pickerConfig: const CameraPickerConfig(enableRecording: true),
  );
}
